package edu.tsp.ga.mutators;

import edu.tsp.ga.Chromosome;
import edu.tsp.ga.Gene;
import edu.tsp.ga.utils.Pair;
import edu.tsp.ga.utils.RandomGenerator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ExchangeMutator implements Mutator {

    @Override
    public Chromosome mutate(Chromosome chromosome) {
        Pair<Integer, Integer> point = RandomGenerator.generateCrossPoints(chromosome.getGenes().size());
        List<Gene> genes = exchangeMutate(chromosome.getGenes(), point.head, point.tail);
        return new Chromosome(genes);
    }

    private <T> List<T> exchangeMutate(List<T> genes, int p1, int p2) {
        List<T> offspring = new ArrayList<>(genes);
        Collections.swap(offspring, p1, p2);
        return offspring;
    }

}
